<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="menuTreeData"
          :replaceFields="{ title: 'menuName', key: 'id' }"
          checkable
          ref="treeRef"
          v-model:checkedKeys="checkedKeys"
          toolbar
          title="菜单分配"
        />
      </template>
      <template #dept="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="deptTreeData"
          :replaceFields="{ title: 'name', key: 'id' }"
          checkable
          toolbar
          title="部门分配"
        />
      </template>
      <template #interface="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="interfaceTreeData"
          :replaceFields="{ title: 'name', key: 'id' }"
          checkable
          toolbar
          title="接口分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';

  import {
    getMenuList,
    getDeptList,
    getItfListByRole,
    getMenuListByRole,
    getDeptListByRole,
    updateRole,
    createRole,
    getItfList,
  } from '/@/api/sys/auth';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();

      const isUpdate = ref(true);
      const menuTreeData = ref<TreeItem[]>([]);
      const deptTreeData = ref<TreeItem[]>([]);
      const interfaceTreeData = ref<TreeItem[]>([]);
      const checkedKeys = ref<Array<number>>([]);
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(menuTreeData).length === 0) {
          menuTreeData.value = (await getMenuList()).records as any as TreeItem[];
        }
        if (unref(deptTreeData.value).length === 0) {
          deptTreeData.value = (await getDeptList()).records as any as TreeItem[];
        }

        if (unref(interfaceTreeData.value).length === 0) {
          interfaceTreeData.value = (await getItfList()).records as any as TreeItem[];
        }
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          //获取当前角色的权限信息
          const id: number = data.record.id;
          const menuIds = (await getMenuListByRole(id)).map((i) => i.id);
          const deptIds = (await getDeptListByRole(id)).map((i) => i.id);
          const itfIds = (await getItfListByRole(id)).map((i) => i.id);
          console.log(menuIds, deptIds);
          setFieldsValue({
            ...data.record,
            menuIds,
            deptIds,
            itfIds,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          unref(isUpdate)
            ? updateRole(values).then(() => {
                createMessage.success('更新成功');
              })
            : createRole(values).then(() => {
                createMessage.success('创建成功');
              });
          console.log(values);
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        menuTreeData,
        deptTreeData,
        checkedKeys,
        interfaceTreeData,
      };
    },
  });
</script>
